package com.xbongbong.help.condition;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.OptionalRangeEnum;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 *  condition条件处理帮助类
 *  （线索分配等场景抽离出的）
 * @author zheng.li
 **/
@Component
public class ConditionHelper {

    @Resource
    private UserModel userModel;

    @Resource
    private DepartmentModel departmentModel;


    /**
     * 员工类型字段组件
     */
    private static final List<Integer> USER_FIELD_LIST = Arrays.asList(FieldTypeEnum.USER.getType(), FieldTypeEnum.USER_GROUP.getType(),
            FieldTypeEnum.CREATORID.getType(), FieldTypeEnum.OWNERID.getType());

    /**
     * 部门类型员工组件
     */
    private static final List<Integer> DEP_FIELD_LIST = Arrays.asList(FieldTypeEnum.DEPT.getType(), FieldTypeEnum.DEPT_GROUP.getType(), FieldTypeEnum.DEPARTMENTID.getType());



    /**
     *  处理员工&部门相关筛选条件(前端回显用)
     *
     *  （根据 com.xbongbong.paas.service.impl.AutomaticallyAssignedServiceImpl#handleUserConditions(java.lang.String, com.alibaba.fastjson.JSONArray)
     *      com.xbongbong.saas.help.PublicSeniorRuleHelp#handleUserConditions(java.lang.String, com.alibaba.fastjson.JSONArray)
     *      com.xbongbong.saas.service.impl.PublicGroupServiceImpl#handleUserOrDepConditions(java.lang.String, com.alibaba.fastjson.JSONArray)
     *      方法抽离出来的方法,以后有缘再优化）
     * @param corpid 公司id
     * @param jsonData 匹配条件 （对应ConditionsEntityExt）
     */
    public void handleUserConditions(String corpid, JSONArray jsonData) {
        // 需要查询的userIds，depIds
        List<String> userIdIn = new ArrayList<>();
        List<Long> depIdIn = new ArrayList<>();
        Map<String, List<String>> userConditionMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String, List<Long>> depConditionMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for(Object obj : jsonData) {
            JSONObject conditionObj = (JSONObject) obj;
            List<Object> valueList;
            try {
                valueList = conditionObj.getJSONArray("value");
            } catch (JSONException e) {
                valueList = null;
            }
            if(Objects.isNull(valueList) || valueList.isEmpty()) {
                continue;
            }
            String attr = conditionObj.getString("attr");
            Integer fieldType = conditionObj.getInteger("fieldType");
            //负责人变前负责人
            if (Objects.equals(attr, ClueEnum.OWNER_ID.getAttr())){
                conditionObj.put(StringConstant.SAAS_LINK_BUSINESS_NAME, I18nMessageUtil.getMessage(I18nStringConstant.PRE_OWNER_ID));
                conditionObj.put(StringConstant.LABEL,I18nMessageUtil.getMessage(I18nStringConstant.PRE_OWNER_ID));
            }
            if(USER_FIELD_LIST.contains(fieldType)) {
                List<String> userIds = new ArrayList<>();
                for(Object userId: valueList) {
                    if (Objects.nonNull(userId)) {
                        userIds.add(userId.toString());
                    }
                }
                userIdIn.addAll(userIds);
                userConditionMap.put(attr, userIds);
            } else if(DEP_FIELD_LIST.contains(fieldType)) {
                List<Long> depIds = new ArrayList<>();
                for(Object depId: valueList) {
                    if (Objects.nonNull(depId)) {
                        depIds.add(Long.parseLong(depId.toString()));
                    }
                }
                depIdIn.addAll(depIds);
                depConditionMap.put(attr, depIds);
            }

        }
        // 查询部门或员工对应的数据
        List<UserEntity> userList;
        List<DepartmentEntity> deptList;
        Map<String, JSONArray> returnMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if(!userIdIn.isEmpty()) {
            userList = userModel.findEntitysByUserIds(userIdIn, corpid);
            for(Map.Entry<String, List<String>> entry : userConditionMap.entrySet()) {
                List<String> valueList = entry.getValue();
                JSONArray returnValueList = new JSONArray();
                for(UserEntity userEntity : userList) {
                    if(valueList.contains(userEntity.getUserId())) {
                        JSONObject object = formReturnData(userEntity.getUserId(),userEntity.getName(),userEntity.getName(),
                                OptionalRangeEnum.USER.getValue(),"user",userEntity.getUserId());
                        returnValueList.add(object);
                    }
                }
                returnMap.put(entry.getKey(), returnValueList);
            }
        }
        if(!depIdIn.isEmpty()) {
            deptList = departmentModel.getByDepIdIn(corpid, depIdIn);
            for(Map.Entry<String, List<Long>> entry : depConditionMap.entrySet()) {
                List<Long> valueList = entry.getValue();
                JSONArray returnValueList = new JSONArray();
                for(DepartmentEntity departmentEntity : deptList) {
                    if(valueList.contains(departmentEntity.getId())) {
                        JSONObject object = formReturnData(departmentEntity.getId(),departmentEntity.getName(),departmentEntity.getName(),
                                OptionalRangeEnum.DEPT.getValue(),"department",departmentEntity.getId());
                        returnValueList.add(object);
                    }
                }
                returnMap.put(entry.getKey(), returnValueList);
            }
        }

        for(Object obj : jsonData) {
            JSONObject conditionObj = (JSONObject) obj;
            String attr = conditionObj.getString("attr");
            if(returnMap.containsKey(attr)) {
                conditionObj.put("value", returnMap.get(attr));
            }
        }
    }

    /**
     * 组装返回数据
     * @param id id
     * @param name name
     * @param label label
     * @param property  property
     * @param type type
     * @param value value
     * @return JSONObject
     */
    private JSONObject formReturnData(Object id,String name,String label,String property,String type,Object value) {
        JSONObject object = new JSONObject();
        object.put("id", id);
        object.put("name",name);
        object.put("label", label);
        object.put("property", property);
        object.put("type", type);
        object.put("value", value);
        return object;
    }

}
